﻿//easyui layout 折叠后显示标题
(function ($) {
    var buttonDir = { north: 'down', south: 'up', east: 'left', west: 'right' };
    $.extend($.fn.layout.paneldefaults, {
        onBeforeCollapse: function () {
            /**/
            var popts = $(this).panel('options');
            var dir = popts.region;
            var btnDir = buttonDir[dir];
            if (!btnDir) return false;

            setTimeout(function () {
                var pDiv = $('.layout-button-' + btnDir).closest('.layout-expand').css({
                    textAlign: 'center', lineHeight: '18px', fontWeight: 'bold'
                });

                if (popts.title) {
                    var vTitle = popts.title;
                    if (dir == "east" || dir == "west") {
                        var vTitle = popts.title.split('').join('<br/>');
                        pDiv.find('.panel-body').html(vTitle);
                    } else {
                        $('.layout-button-' + btnDir).closest('.layout-expand').find('.panel-title')
                        .css({ textAlign: 'left' })
                        .html(vTitle)
                    } 
                }
            }, 100); 
        }
    });
})(jQuery);

//扩展datagrid动态处理toolbar方法
//$('#tt').datagrid("addToolbarItem", [{ "text": "xxx" }, "-", { "text": "xxxsss", "iconCls": "icon-ok" }])
//$('#tt').datagrid("removeToolbarItem", "GetChanges")//根据btn的text删除
//$('#tt').datagrid("removeToolbarItem", 0)//根据下标删除
//$('#tt').datagrid("removeToolbar")//删除所有
$(function () {
    $.extend($.fn.datagrid.methods, {
        addToolbarItem: function (jq, items) {
            return jq.each(function () {
                var toolbar = $(this).parent().prev("div.datagrid-toolbar");
                for (var i = 0; i < items.length; i++) {
                    var item = items[i];
                    if (item === "-") {
                        toolbar.append('<div class="datagrid-btn-separator"></div>');
                    } else {
                        var btn = $("<a href=\"javascript:void(0)\"></a>");
                        btn[0].οnclick = eval(item.handler || function () { });
                        btn.css("float", "left").appendTo(toolbar).linkbutton($.extend({}, item, { plain: true }));
                    }
                }
                toolbar = null;
            });
        },
        removeToolbar: function (jq) {
            return jq.each(function () {
                var btns = $(this).parent().prev("div.datagrid-toolbar").find("a");
                var cbtn = null;
                for (var i = 0; i < btns.length; i++) {
                    var cbtn = btns.eq(i);
                    if (cbtn) {
                        var prev = cbtn.prev()[0];
                        var next = cbtn.next()[0];
                        if (prev && next && prev.nodeName == "DIV" && prev.nodeName == next.nodeName) {
                            $(prev).remove();
                        } else if (next && next.nodeName == "DIV") {
                            $(next).remove();
                        } else if (prev && prev.nodeName == "DIV") {
                            $(prev).remove();
                        }
                        cbtn.remove();                        
                    }
                }
              
            });
        },
        removeToolbarItem: function (jq, param) {
            return jq.each(function () {
                var btns = $(this).parent().prev("div.datagrid-toolbar").find("a");
                var cbtn = null;
                if (typeof param == "number") {
                    cbtn = btns.eq(param);
                } else if (typeof param == "string") {
                    var text = null;
                    btns.each(function () {
                        text = $(this).data().linkbutton.options.text;
                        console.log(text);
                        if (text == param) {
                            cbtn = $(this);
                            text = null;
                            return;
                        }
                    });
                }
                if (cbtn) {
                    var prev = cbtn.prev()[0];
                    var next = cbtn.next()[0];
                    if (prev && next && prev.nodeName == "DIV" && prev.nodeName == next.nodeName) {
                        $(prev).remove();
                    } else if (next && next.nodeName == "DIV") {
                        $(next).remove();
                    } else if (prev && prev.nodeName == "DIV") {
                        $(prev).remove();
                    }
                    cbtn.remove();
                    cbtn = null;
                }
            });
        }
    });
});




//在iframe中调用，在父窗口中出提示框(herf方式不用调父窗口)
$.extend({
    show_warning: function (strTitle, strMsg) {
        $.messager.show({
            title: strTitle,
            width: 300,
            height: 100,
            msg: strMsg,
            closable: true,
            showType: 'slide',
            style: {
                right: '',
                top: document.body.scrollTop + document.documentElement.scrollTop,
                bottom: ''
            }
        });
    }
});

//弹框
$.extend({
    show_alert: function (strTitle, strMsg) {
        $.messager.alert(strTitle, strMsg);
    }
});

//扩展validatebox，添加验证
$.extend($.fn.validatebox.defaults.rules, {
    eqPwd: {
        validator: function (value, param) {
            return value == $(param[0]).val();
        },
        message: '密码不一致！'
    },
    idcard: {// 验证身份证
        validator: function (value) {
            return /^\d{15}(\d{2}[A-Za-z0-9])?$/i.test(value);
        },
        message: '身份证号码格式不正确'
    },
    minLength: {
        validator: function (value, param) {
            return value.length >= param[0];
        },
        message: '请输入至少 {0} 个字符.'
    },
    length: {
        validator: function (value, param) {
            var len = $.trim(value).length;
            return len >= param[0] && len <= param[1];
        },
        message: "必须介于{0}和{1}之间."
    },
    phone: {// 验证电话号码
        validator: function (value) {
            return /^((\d2,3)|(\d{3}\-))?(0\d2,3|0\d{2,3}-)?[1-9]\d{6,7}(\-\d{1,4})?$/i.test(value);
        },
        message: '格式不正确,请使用下面格式:020-88888888'
    },
    mobile: {// 验证手机号码
        validator: function (value) {
            return /^(13|15|18)\d{9}$/i.test(value);
        },
        message: '手机号码格式不正确'
    },
    intOrFloat: {// 验证整数或小数
        validator: function (value) {
            return /^\d+(\.\d+)?$/i.test(value);
        },
        message: '请输入数字，并确保格式正确'
    },
    currency: {// 验证货币
        validator: function (value) {
            return /^\d+(\.\d+)?$/i.test(value);
        },
        message: '货币格式不正确'
    },
    qq: {// 验证QQ,从10000开始
        validator: function (value) {
            return /^[1-9]\d{4,9}$/i.test(value);
        },
        message: 'QQ号码格式不正确'
    },
    integer: {// 验证整数 可正负数
        validator: function (value) {
            //return /^[+]?[1-9]+\d*$/i.test(value);

            return /^([+]?[0-9])|([-]?[0-9])+\d*$/i.test(value);
        },
        message: '请输入整数'
    },
    age: {// 验证年龄
        validator: function (value) {
            return /^(?:[1-9][0-9]?|1[01][0-9]|120)$/i.test(value);
        },
        message: '年龄必须是0到120之间的整数'
    },

    chinese: {// 验证中文
        validator: function (value) {
            return /^[\Α-\￥]+$/i.test(value);
        },
        message: '请输入中文'
    },
    english: {// 验证英语
        validator: function (value) {
            return /^[A-Za-z]+$/i.test(value);
        },
        message: '请输入英文'
    },
    unnormal: {// 验证是否包含空格和非法字符
        validator: function (value) {
            return /.+/i.test(value);
        },
        message: '输入值不能为空和包含其他非法字符'
    },
    username: {// 验证用户名
        validator: function (value) {
            return /^[a-zA-Z][a-zA-Z0-9_]{5,15}$/i.test(value);
        },
        message: '用户名不合法（字母开头，允许6-16字节，允许字母数字下划线）'
    },
    dbname: {// 验证字段表名
        validator: function (value) {
            return /^[a-zA-Z][a-zA-Z0-9]{3,19}$/i.test(value);
        },
        message: '输入不合法（字母开头，允许4-20字节，允许字母数字）'
    },
    faxno: {// 验证传真
        validator: function (value) {
            return /^((\d2,3)|(\d{3}\-))?(0\d2,3|0\d{2,3}-)?[1-9]\d{6,7}(\-\d{1,4})?$/i.test(value);
        },
        message: '传真号码不正确'
    },
    zip: {// 验证邮政编码
        validator: function (value) {
            return /^[1-9]\d{5}$/i.test(value);
        },
        message: '邮政编码格式不正确'
    },
    ip: {// 验证IP地址
        validator: function (value) {
            return /d+.d+.d+.d+/i.test(value);
        },
        message: 'IP地址格式不正确'
    },
    name: {// 验证姓名，可以是中文或英文
        validator: function (value) {
            return /^[\Α-\￥]+$/i.test(value) | /^\w+[\w\s]+\w+$/i.test(value);
        },
        message: '请输入姓名'
    },
    date: {// 验证姓名，可以是中文或英文
        validator: function (value) {
            //格式yyyy-MM-dd或yyyy-M-d
            return /^(?:(?!0000)[0-9]{4}([-]?)(?:(?:0?[1-9]|1[0-2])\1(?:0?[1-9]|1[0-9]|2[0-8])|(?:0?[13-9]|1[0-2])\1(?:29|30)|(?:0?[13578]|1[02])\1(?:31))|(?:[0-9]{2}(?:0[48]|[2468][048]|[13579][26])|(?:0[48]|[2468][048]|[13579][26])00)([-]?)0?2\2(?:29))$/i.test(value);
        },
        message: '清输入合适的日期格式'
    },
    msn: {
        validator: function (value) {
            return /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/.test(value);
        },
        message: '请输入有效的msn账号(例：abc@hotnail(msn/live).com)'
    },
    same: {
        validator: function (value, param) {
            if ($("#" + param[0]).val() != "" && value != "") {
                return $("#" + param[0]).val() == value;
            } else {
                return true;
            }
        },
        message: '两次输入的密码不一致！'
    }
});

//接收一个以逗号分割的字符串，返回List，list里每一项都是一个字符串（做编辑功能的时候 传入id 然后自动勾选combo系列组件）
stringToList = function (value) {
    if (value != undefined && value != '') {
        var values = [];
        var t = value.split(',');
        for (var i = 0; i < t.length; i++) {
            values.push('' + t[i]); /* 避免将ID当成数字 */
        }
        return values;
    } else {
        return [];
    }
};

//生成datagrid单据统一按钮
getToolBar = function (data) {
    if (data.toolbar != undefined && data.toolbar != '') {
        var toolbar = [];
        $.each(data.toolbar, function (index, row) {
            var handler = row.handler;
            row.handler = function () { eval(handler); };
            toolbar.push(row);
        });
        return toolbar;
    } else {
        return [];
    }
};
//生成div单据统一按钮
getToolBarDiv = function (data) {
if (data.toolbar != undefined && data.toolbar != '') {
        var toolbar = "";
        $.each(data.toolbar, function (index, row) {
           // ' <a href="#" class="easyui-linkbutton" title="'+row.text+'" data-options="iconCls:\''+row.iconCls+'\',plain:true" onClick="javascript:'+row.handler+'">'+row.text+'</a> '
            toolbar += '<a href="#" class="easyui-linkbutton l-btn l-btn-small l-btn-plain" title="' + row.text + '" data-options="iconCls:\'' + row.iconCls + '\', plain:true" onclick="javascript:' + row.handler + ';" ><span class="l-btn-left l-btn-icon-left"><span class="l-btn-text">' + row.text + '</span><span class="l-btn-icon ' + row.iconCls + '">&nbsp;</span></span></a>';
        });
        return toolbar;
    } else {
        return "";
    }
};

//表格内容的格式控制
//返回日期；
getDate = function (value, row, index) { if (value) { return value.substring(0, value.indexOf(' ')) } else { return "" } };
//显示长字符串；
showLongString = function (value, row, index) { if (value) { return value.length > 8 ? '<span title="' + value + '">' + value + '</span>' : value;} else { return "" }};
//返回两位小数的金额；
getCurrency = function (value, row, index) { if (value) { return value.toFixed(2) } else { return "0.00" }};
//返回1位小数的百分数；
getPercent = function (value, row, index) { if (value) { return Number(value * 100).toFixed(1) + "%" } else { return "-" }};


initDatagrid = function (KeyName,myColums,eID,url) {
        $.ajax({     //请求当前用户可以操作的按钮
            url: "/Button/GetUserAuthorizeButton?r=" + Math.random(),
            type: "post",
            data: { KeyName: KeyName,KeyCode:KeyName },
            dataType: "json",
            timeout: 5000,
            success: function (data) {
                if (data.success) {
                    var toolbar = getToolBar(data);      //common.js
                    if (data.search) {     //判断是否有浏览权限
                        $(eID).datagrid({
                            url: url,
                            striped: true, rownumbers: true, pagination: true, pageSize: 20, singleSelect: true,
                            fitColumns: false,
                            //idField: 'FBillNo',
                            //sortName: 'dept',
                            //sortOrder: 'desc',
                            pageList: [20, 40, 60, 80, 100],
                            frozenColumns: [],
                            columns: myColums,
                            toolbar: toolbar.length == 0 ? null : toolbar
                        });
                    }
                    else {
                        $.show_alert("提示", "无权限，请联系管理员！");
                    }
                } else {
                    $.show_alert("错误", data.result);
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                if (textStatus == "timeout") {
                    $.show_alert("提示", "请求超时，请刷新当前页重试！");
                }
                else {
                    $.show_alert("错误", textStatus + "：" + errorThrown);
                }
            }
        }) 
};
 
//ajax下模拟表单方式下载文件
download = function(url, data, method) {
    //url and data options required 
    if (url && data) {
        //data can be string of parameters or array/object 
        data = typeof data == 'string' ? data : jQuery.param(data);
        //split params into form inputs 
        var inputs = '';
        jQuery.each(data.split('&'), function () {
            var pair = this.split('=');
            inputs += '<input type="hidden" name="' + pair[0] + '" value="' + pair[1] + '" />';
        });
        //send request 
        jQuery('<form action="' + url + '" method="' + (method || 'post') + '">' + inputs + '</form>')
        .appendTo('body').submit().remove();
    };
};

var DateUtils = {
    GetPercent:function(num, total) {
/// <summary>
/// 求百分比
/// </summary>
/// <param name="num">当前数</param>
/// <param name="total">总数</param>
    num = parseFloat(num);
    total = parseFloat(total);
    if (isNaN(num) || isNaN(total)) {
        return "-";
    }
    return total <= 0 ? "0%" : (Math.round(num / total * 10000) / 100.00) + "%";
    },
};

//以下为三种字符串格式化方法
//两种调用方式
//var template1 = "我是{0}，今年{1}了";
//var template2 = "我是{name}，今年{age}了";
//var result1 = template1.format("loogn", 22);
//var result2 = template2.format({ name: "loogn", age: 22 });
//两个结果都是"我是loogn，今年22了
String.prototype.format = function (args) {
    var result = this;
    if (arguments.length > 0) {
        if (arguments.length == 1 && typeof (args) == "object") {
            for (var key in args) {
                if (args[key] != undefined) {
                    var reg = new RegExp("({" + key + "})", "g");
                    result = result.replace(reg, args[key]);
                }
            }
        }
        else {
            for (var i = 0; i < arguments.length; i++) {
                if (arguments[i] != undefined) {
                    //var reg = new RegExp("({[" + i + "]})", "g");//这个在索引大于9时会有问题
                    var reg = new RegExp("({)" + i + "(})", "g");
                    result = result.replace(reg, arguments[i]);
                }
            }
        }
    }
    return result;
}

//StringFormat("&Type={0}&Ro={1}&lPlan={2}&Plan={3}&={4}&Id={5}&Id={6}", data1, data2, data3, data4, data5, data6, data7);
stringFormat=function() {
    if (arguments.length == 0)
        return null;
    var str = arguments[0];
    for (var i = 1; i < arguments.length; i++) {
        var re = new RegExp('\\{' + (i - 1) + '\\}', 'gm');
        str = str.replace(re, arguments[i]);
    }
    return str;
}
//element.innerHTML = String.format(’<a href=”%1″ οnclick=”alert(\’%2\’);”>%3</a>’, url, msg, text);
String.format = function(str) {
    var args = arguments, re = new RegExp("%([1-" + args.length + "])", "g");
    return String(str).replace(
		re,
		function($1, $2) {
		    return args[$2];
		}
	);
};

getQueryVariable=function(variable) {
    var query = window.location.search.substring(1);
    var vars = query.split("&");
    for (var i = 0; i < vars.length; i++) {
        var pair = vars[i].split("=");
        if (pair[0] == variable) { return pair[1]; }
    }
    return (null);
}


//传参：
//location.href = "http://localhost:3207/MemberMgr/WashCar.html?deId=" + deId + "&deName=" + encodeURI(deName);//解决中文乱码
//接收：//截取url的参数，当没有参数时，按索引2读取会报错！
function GetQueryString(parameter) {
    var reg = new RegExp("(^|&)" + parameter + "=([^&]*)(&|$)");
    var r = window.location.search.substr(1).match(reg);
    return r[2];
    //if (r != null) { 
    //    if (parameter == "deId") {
    //        $("#deId").val(r[2]);
    //    }
    //    if (parameter == "deName") {
    //        $("#deName").val(decodeURI(r[2]));//解决中文乱码
    //    }
    //}
}
//生成uuid，调用方法：uuid(8, 2)  //  "01001010"  uuid(8, 10) // "47473046"  uuid(8, 16) // "098F4D35"
function uuid(len, radix) {
    var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');
    var uuid = [], i;
    radix = radix || chars.length; 
    if (len) {
        // Compact form
        for (i = 0; i < len; i++) uuid[i] = chars[0 | Math.random()*radix];
    } else {
        // rfc4122, version 4 form
        var r;
        // rfc4122 requires these characters
        uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-';
        uuid[14] = '4';
        // Fill in random data.  At i==19 set the high bits of clock sequence as
        // per rfc4122, sec. 4.1.5
        for (i = 0; i < 36; i++) {
            if (!uuid[i]) {
                r = 0 | Math.random()*16;
                uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];
            }
        }
    }
    return uuid.join('');
}

//datagrid行移动
function MoveUp() {
    var row = $("#Student_Table").datagrid('getSelected');
    var index = $("#Student_Table").datagrid('getRowIndex', row);
    mysort(index, 'up', 'Student_Table');     
}
//下移
function MoveDown() {
    var row = $("#Student_Table").datagrid('getSelected');
    var index = $("#Student_Table").datagrid('getRowIndex', row);
    mysort(index, 'down', 'Student_Table');     
}  
function mysort(index, type, gridname) {
    if ("up" == type) {
        if (index != 0) {
            var toup = $('#' + gridname).datagrid('getData').rows[index];
            var todown = $('#' + gridname).datagrid('getData').rows[index - 1];
            $('#' + gridname).datagrid('getData').rows[index] = todown;
            $('#' + gridname).datagrid('getData').rows[index - 1] = toup;
            $('#' + gridname).datagrid('refreshRow', index);
            $('#' + gridname).datagrid('refreshRow', index - 1);
            $('#' + gridname).datagrid('selectRow', index - 1);
        }
    } else if ("down" == type) {
        var rows = $('#' + gridname).datagrid('getRows').length;
        if (index != rows - 1) {
            var todown = $('#' + gridname).datagrid('getData').rows[index];
            var toup = $('#' + gridname).datagrid('getData').rows[index + 1];
            $('#' + gridname).datagrid('getData').rows[index + 1] = todown;
            $('#' + gridname).datagrid('getData').rows[index] = toup;
            $('#' + gridname).datagrid('refreshRow', index);
            $('#' + gridname).datagrid('refreshRow', index + 1);
            $('#' + gridname).datagrid('selectRow', index + 1);
        }
    }
}